<template>
  <div class="emp-comtainer">

    <!-- 1
    <PageTools>
      <el-button slot="left" type="primary">按钮</el-button>
      <template slot="right">
        <el-button type="primary">按钮111</el-button>
        <el-button type="primary">按钮</el-button>
      </template>

    </PageTools>

    <PageTools>
      <el-alert slot="left" title="警告提示的文案" type="warning" show-icon />
      <template slot="right">
        <span>设置</span>
        <span>2021-08</span>
      </template>

    </PageTools> -->
    <!-- <PageTools>
      <!-- <el-button slot="left" type="primary">按钮</el-button>
      <template slot="right">
        <el-button type="primary">按钮111</el-button>
        <el-button type="primary">按钮</el-button>
      </template>
      <el-button slot="left" type="primary">按钮</el-button>
      <!-- <template #right>
        <el-button type="primary">按钮111</el-button>
        <el-button type="primary">按钮</el-button>
      </template>
      <template v-slot:right>
        <el-button type="primary">按钮111</el-button>
        <el-button type="primary">按钮</el-button>
      </template>

    </PageTools>

		</PageTools> -->
    <PageTools>
      <template #right>
        <el-button size="mini" type="primary" @click="$router.push({path:'/employees/import',query:{name:'员工'}})">导入
        </el-button>
        <el-button size="mini" type="success" @click="handleDownload">导出</el-button>
        <el-button size="mini" type="primary">+ 新增员工</el-button>
      </template>
    </PageTools>

    <el-card>
      <el-table border :data="tableData" style="width: 100%">
        <!-- <el-table-column type="index" width="50" label="序号" /> -->
        <el-table-column width="50" label="序号">
          <template slot-scope="{$index}">
            <i>{{ (queryObj.page-1)*(queryObj.size)+$index+1 }}==</i>
          </template>

        </el-table-column>
        <el-table-column sortable prop="username" label="姓名" width="150" />
        <el-table-column label="图像" width="150">
          <template slot-scope="scope">
            <img
              v-imgError
              style="width:80px;height:80px;border-radius:50%"
              :src="scope.row.staffPhoto"
              alt=""
              @click="showQrcodeHandle"
            >
          </template>
        </el-table-column>
        <el-table-column sortable prop="mobile" label="手机号" width="150" />
        <el-table-column sortable prop="workNumber" label="工号" width="150" />
        <el-table-column sortable prop="formOfEmployment" label="聘用形式" width="150" />
        <el-table-column sortable prop="departmentName" label="部门" width="150" />
        <el-table-column sortable label="入职时间" width="350">
          <template slot-scope="scope">
            <span>{{ scope.row.timeOfEntry | forTime }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable label="是否在职" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.enableState==1?'在职':'离职' }}</span>=={{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column sortable prop="inServiceStatus" label="状态" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.inServiceStatus==1?'可用':'不可用' }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="280">
          <template slot-scope="{row}">
            <!-- <el-button @click='$router.push("/employees/detail/"+row.id)' type="text" size="small"> -->
            <el-button type="text" size="small" @click="$router.push({name:&quot;detail&quot;,params:{id:row.id}})">
              查看
            </el-button>
            <el-button type="text" size="small">
              转正
            </el-button>
            <el-button type="text" size="small">
              调岗
            </el-button>
            <el-button type="text" size="small">
              离职
            </el-button>
            <el-button type="text" size="small" @click="ruleBtn(row.id)">
              角色
            </el-button>

            <el-button type="text" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="queryObj.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryObj.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 角色对话框 -->
      <el-dialog title="提示" :visible.sync="dialogVisibleRule" width="70%">
        <el-form>
          <el-checkbox-group v-model="form.roleIds">
            <el-checkbox v-for="(item,index) in roleList " :key="index" :label="item.id" name="type">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
          <!-- =={{ form.roleIds }} -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleRule = false">取 消</el-button>
          <el-button type="primary" @click="setRoleHandle">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>

    <!-- 显示二维码对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisibleCode" width="40%">
      <canvas id="canvas" ref="canvas" style="text-align:center" />
    </el-dialog>

  </div>
</template>

<script>
import {
  formatDate
} from '@/utils'
import {
  parseTime
} from '@/utils'
import {
  getEmployeeList,
  assignRoles
} from '@/api/employees'
import {
  getUserDetailById
} from '@/api/user'
import {
  getRoleList
} from '@/api/setting'

import QRCode from 'qrcode'
export default {
  name: '',
  data() {
    return {
      tableData: [],
      queryObj: {
        page: 1,
        size: 10
      },
      queryRuleObj: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      roleList: [],
      dialogVisibleRule: false,
      form: {
        id: '',
        roleIds: []
      },

      /* 导出 */
      filename: '63期花名册',
      autoWidth: true,
      bookType: 'xlsx',
      dialogVisibleCode: false
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    async getEmployee() {
      const res = await getEmployeeList(this.queryObj)
      console.log(res, 22333)
      this.tableData = res.rows
      this.total = res.total
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryObj.size = val
      this.getEmployee()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryObj.page = val
      this.getEmployee()
    },
    //  获取角色列表
    //  获取角色列表
    async getRList() {
      const {
        rows
      } = await getRoleList(this.queryRuleObj)
      this.roleList = rows
    },
    //  点击员工中的角色按钮
    async ruleBtn(id) {
      //  需要发送两个请求  2个  请求1：获取所有的角色列表  请求2：获取当前用户所拥有的角色集合
      // console.log(id, 77777)
      //  获取当前用户所拥有的角色集合
      this.form.id = id
      const {
        roleIds
      } = await getUserDetailById(id) //  获取当前用户所拥有的角色
      this.form.roleIds = roleIds
      //  获取所有的角色列表
      this.getRList()
      this.dialogVisibleRule = true
    },
    //  点击对话框确认按钮
    async setRoleHandle() {
      await assignRoles(this.form)
      this.dialogVisibleRule = false
    },

    /* 导出 */
    handleDownload() {
      var obj = {
        '入职日期': 'correctionTime',
        '手机号': 'mobile',
        '转正日期': 'timeOfEntry',
        '姓名': 'username',
        '工号': 'workNumber'
      }

      // this.downloadLoading = true
      import('@/vendor/Export2Excel').then(async excel => {
        // const tHeader = ['序号', '姓名', '入职日期', '转正日期', '工号']
        const tHeader = Object.keys(obj)
        // const filterVal = ['id', 'username', 'correctionTime', 'timeOfEntry', 'workNumber']
        const filterVal = Object.values(obj) //  [correctionTime,mobile,timeOfEntry,username,workNumber]
        const res = await getEmployeeList({
          page: 1,
          size: this.total
        }) // 获取总条数
        const list = res.rows
        // const list = this.tableData //  只获取10条
        // console.log(list, 9999)
        const data = this.formatJson(filterVal, list)
        console.log(data, 445566)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          multiHeader: [
            [1, 22, 3, 4, 5, 6, 7],
            ['主要信息', 2, '', '', 4, 5, 6],
            ['姓名1', '主要信息', '', '', '', '', '部门'],
            ['姓名', '主要信息', '', '', '', '', '部门']
          ],
          // multiHeader: [[1, 2, 3, 4, 5]],
          merges: ['B1:B3'],
          filename: this.filename, //  文件名
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        // this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => {
        return filterVal.map(k => { //  correctionTime,mobile,timeOfEntry,username,workNumber
          // if (k === 'correctionTime' || k === 'timeOfEntry') {
          //   return v[k]
          // } else {
          //   return v[k] //  {}
          // }
          return v[k]
        })

        // return v[]
      })

      //  [{}]

      // var newArr = jsonData.map(v => filterVal.map(j => {
      //   if (j === 'timestamp') {
      //     return parseTime(v[j])
      //   } else {
      //     return v[j] //   {'id', 'mobile', 'correctionTime', 'timeOfEntry', 'username', 'workNumber'}
      //   }
      // }))

      // return newArr //  [ {'id', 'mobile', 'correctionTime', 'timeOfEntry', 'username', 'workNumber'},{}]
    },

    //  显示对话框
    showQrcodeHandle() {
      // dialogVisibleCode: false
      this.dialogVisibleCode = true
      //
      var url = 'https://s3.bmp.ovh/imgs/2021/08/15d675ee104bb8ea.jpeg'
      /*
			只要结构是动态生成的 获取dom是直接获取不到的  需要使用  nextTick才可以获取
		也可以使用定时器来实现
			 */

      this.$nextTick(() => {
        var canvasRef = this.$refs.canvas
        console.log(canvasRef, 44556)
        QRCode.toCanvas(canvasRef, url)
        // QRCode.toCanvas(canvasRef,'sample text')
      })
    }
  }
}

</script>
<style lang='scss' scoped>
  .emp-comtainer {
    ::v-deep .el-dialog__body {
      display: flex;
      justify-content: center;
    }
  }

</style>
